<template>
  <div class="template-content">
    <SearchHeader v-model="queryParam.where.keyword" :can-add="canModify" @handleSearch="getData" @handleAdd="add" @handleInit="queryParam.init">
      <Row :gutter="4" >
        <Col span="6"><Input :placeholder="$t('code')" v-model="queryParam.where.code"></Input> </Col>
        <Col span="6"><Input :placeholder="$t('name')" v-model="queryParam.where.name"></Input> </Col>
        <Col span="6"><OrganizationTree v-model="queryParam.where.parentId" ref="srhParent" :placeholder="$t('parent')"></OrganizationTree> </Col>
<!--        <Col span="1"><Button type="primary" @click="getData">查询</Button></Col>-->
      </Row>
    </SearchHeader>
    <Card>
      <Table row-key="id" :load-data="getChild" ref="table" :columns="columns" :data="tableData" border>
        <template slot-scope="{ row, index }" slot="action">
          <Button type="default" :disabled="!canModify" :Title="$t('add_child')" icon="ios-add"  style="margin-right: 5px" @click="add(row)"></Button>
          <Button type="default" :disabled="!canModify" :Title="$t('edit')" icon="md-create" style="margin-right: 5px" @click="edit(row)"></Button>
          <Button type="default" :disabled="!canModify" :Title="$t('delete')" icon="md-trash"  @click="remove(row)"></Button>
        </template>
      </Table>
      <TopnavPage v-model="queryParam.page" @changePage="getData"></TopnavPage>
<!--      <page class="panel-page" :total="queryParam.page.total"
            :current="queryParam.page.pages"
            :page-size="queryParam.page.size"
            :page-size-opts="pageizeOpts"
            @on-change="changePage" show-elevator show-sizer show-total></page>-->
    </Card>
<!--    <Modal v-model="addModal" :loading="modalLoading" title=""  @on-ok="addOk"  @on-cancel="cancel" okText="$t('save')"> &lt;!&ndash; footer-hide="false" &ndash;&gt;
      <Form :model="rowData" label-position="right" :label-width="80">
        <FormItem :label="$t('code')"><Input v-model="rowData.code"></Input></FormItem>
        <FormItem :label="$t('name')"><Input v-model="rowData.name"></Input></FormItem>
        <FormItem :label="$t('short_name')"><Input v-model="rowData.shortName"></Input></FormItem>
        <FormItem :label="$t('parent')"><OrganizationTree v-model="rowData.parentId" width="200px" ref="edtParent"></OrganizationTree></FormItem>
      </Form>
    </Modal>-->
    <OrganizationEdit ref = "organizationEdit"></OrganizationEdit>
  </div>
</template>
<script>
import {addOrg, updateOrg,removeOrg,queryToplayerPage, queryChildrens} from '@/api/Organization';
import TopnavPage from "_c/topnav/TopnavPage";
import SearchHeader from "@/view/Common/SearchHeader";
import OrganizationEdit from '@/view/Organization/OrganizationEdit';
import OrganizationTree from '@/components/topnav/OrganizationTree';
import AuthCheck from "@/api/AuthCheck";
import {apiResult} from "@/libs/util";
export default {
  name: "Organization",
  components: {OrganizationTree,TopnavPage,SearchHeader,OrganizationEdit},
  computed:{
    columns(){
      return[
        { title: this.$t('code'), key: 'code', sortable: true, width: 175,tree: true },
        { title: this.$t('name'), key: 'name', sortable: false, width: 250 },
        { title: this.$t('short_name'), key: 'shortName', sortable: false, width: 250 },
        { title: this.$t('parent'), key: 'parentName', resizable: true,sortable: false, width: 200 },
        { title: this.$t('operate'), key: 'action', width: 200, slot: 'action'}
      ]
    }
  },
  data(){
    return{
      canModify: false,
      pageizeOpts:[10,15,20,30,40,100],
      queryParam:{
        page: {
          current: 1,
          desc: ['create_time'],
          maxLimit: 10000,
          optimizeCountSql: true,
          pages: 0,
          searchCount: true,
          size: 15,
          total: 0
        },
        where: {
          keyword: null,
          code: null,
          name: null,
          parentId: null,
          toplayer: false
        },
        init:()=>{
          this.queryParam.where.keyword=null;
          this.queryParam.where.code=null;
          this.queryParam.where.name=null;
          this.queryParam.where.parentId=null;
          this.queryParam.where.toplayer =false;
        }
      },
      rowData: {
        code: null,
        id: null,
        name: null,
        parentId: null,
        parentName: null,
        path: null,
        shortName: null,
        groupTalkUser: null,
        groupTalkPswd: null
      },
      tableData: [],
      addModal: false,
      modalLoading: false,
    }
  },
  methods: {
    getData() {
      this.tableData = [];

      if (!this.queryParam.where.keyword && !this.queryParam.where.code
        && !this.queryParam.where.name && !this.queryParam.where.parentId) {
        this.queryParam.where.toplayer = true
      } else {
        this.queryParam.where.toplayer = false
      }
      queryToplayerPage(JSON.stringify(this.queryParam)).then(res => {
        apiResult(res.data, false,result => {
          this.queryParam.page.total = result.data.total;
          let datas = [];
          for (let i in result.data.records) {
            const o = result.data.records[i];
            if (o.hasChildrens === true) {
              let d = {
                id: o.id,
                code: o.code,
                name: o.name,
                shortName: o.shortName,
                path: o.path,
                parentId: o.parentId,
                parentName: o.parent == null ? null : o.parent.name,
                groupTalkUser: o.groupTalkUser,
                groupTalkPswd: o.groupTalkPswd,
                _loading: false,
                children: []
              }
              datas.push(d);
            } else {
              let d = {
                id: o.id,
                code: o.code,
                name: o.name,
                shortName: o.shortName,
                path: o.path,
                parentId: o.parentId,
                parentName: o.parent == null ? null : o.parent.name,
                groupTalkUser: o.groupTalkUser,
                groupTalkPswd: o.groupTalkPswd,
              }
              datas.push(d);
            }
            this.tableData = datas;
          }
        })
      })
    },
    initRowData() {
      let rowD =
        {
          id:null,
          code: null,
          name: null,
          parentId: null,
          parentName: null,
          path: null,
          shortName: null,
          groupTalkUser: null,
          groupTalkPswd: null,
        }
      return  rowD;
    },
    add(row) {
      if (!!row) {
        //下级
        row._showChildren=true;
        this.$refs.organizationEdit.openDialog("ADD",row,
          (data)=>{
             if (!data){return;}

             let d = {
                 id: data.id,
                 code: data.code,
                 name: data.name,
                 shortName: data.shortName,
                 path: data.path,
                 parentId: data.parentId,
                 parentName: data.parent == null ? null : data.parent.name,
                 groupTalkUser: data.groupTalkUser,
                 groupTalkPswd: data.groupTalkPswd,
               }
             if (data.hasChildrens == true){
               d.children= [];
             }
             let children=[];
             if (!!row.children){
               children=row.children;
             }
             children.push(d);
             row.children = children;
          }
        );
      }else{
        this.$refs.organizationEdit.openDialog("ADD",this.initRowData(),
        (data)=>{
          if (!data){return;}
          if (!data.parentId){
            this.getData();
          }
        });
      }


/*
      console.log(row);
      this.modalLoading = true;
      this.addModal = false;
      this.rowData = this.initRowData();
      if (!!row) {
        this.edtParentId = row.id;
        this.$refs.edtParent.setValue(row.id);
      }else{
        this.$refs.edtParent.setValue(null);
      }
      this.addModal = true;
*/
    },
    edit(row) {
      console.log(row);
      this.$refs.organizationEdit.openDialog("EDIT",row,
        (data)=>{
          //console.log("row:%o",row);
          //console.log("data:%o",data);
          row.code = data.code;
          row.name = data.name;
          row.parentId = data.parentId;
          row.shortName = data.shortName;
          row.groupTalkUser = data.groupTalkUser;
          row.groupTalkPswd = data.groupTalkPswd;
        });
    },

    cancel() {
      this.addModal = false;
    },
    remove(row) {
      this.$Modal.confirm({
        title: '删除确认',
        content: '<p>确定要删除此项？</p',
        onOk:(() => {
          removeOrg(JSON.stringify(row)).then(res=>{  //特别注意此 then(res=>...) 误写成 then()(res=>... 报错
            apiResult(res.data,true,result=>{
              this.getData();
            })
          })
        }),
        onCancel: (() => {
        })
      });
    },
    getChild(item, callback) {
      console.log("callback= %o",callback);
      //console.log(item);
      let datas = [];
      queryChildrens(JSON.stringify({parentId:item.id})).then(res => {
        apiResult(res.data,false,result=>{
          for (let i in res.data.data) {
            var o = res.data.data[i];
            if (o.hasChildrens == true) {
              var d = {
                id: o.id,
                code: o.code,
                name: o.name,
                shortName: o.shortName,
                path: o.path,
                parentId: o.parentId,
                _loading: false,
                children: [],
                parentName: o.parent == null ? null : o.parent.shortName,
                groupTalkUser : o.groupTalkUser,
                groupTalkPswd : o.groupTalkPswd,
              }
              datas.push(d);
            } else {
              var d = {
                id: o.id,
                code: o.code,
                name: o.name,
                shortName: o.shortName,
                path: o.path,
                parentId: o.parentId,
                parentName: o.parent == null ? null : o.parent.shortName,
                groupTalkUser : o.groupTalkUser,
                groupTalkPswd : o.groupTalkPswd,
              }
              datas.push(d);
            }
          }
          callback(datas);
        });
        /*if (res.data.code === 0) {
          for (let i in res.data.data) {
            var o = res.data.data[i];
            if (o.hasChildrens == true) {
              var d = {
                id: o.id,
                code: o.code,
                name: o.name,
                shortName: o.shortName,
                path: o.path,
                parentId: o.parentId,
                _loading: false,
                children: [],
                parentName: o.parent == null ? null : o.parent.shortName,
                groupTalkUser : o.groupTalkUser,
                groupTalkPswd : o.groupTalkPswd,
              }
              datas.push(d);
            } else {
              var d = {
                id: o.id,
                code: o.code,
                name: o.name,
                shortName: o.shortName,
                path: o.path,
                parentId: o.parentId,
                parentName: o.parent == null ? null : o.parent.shortName,
                groupTalkUser : o.groupTalkUser,
                groupTalkPswd : o.groupTalkPswd,
              }
              datas.push(d);
            }
          }
          callback(datas);
          console.log(datas);
        }*/

      });

    },
  },
  mounted (){
    this.canModify = new AuthCheck().organizationRegEdit();
    this.getData();
  },
}

</script>
<style lang="less">
@import ".././template";
@import "../style/view-table";
@import "Organization";
.ivu-table .error td{
  color: red;
}
.expand-key {
  font-weight: bold;
}
.action-style{
  width: 50px;
  height: 30px;
  borderRadius: 5px
}
</style>
